package com.hxzy.util;

import cn.hutool.json.JSONUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

import static org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes;

public class ServletUtil {

    /**
     * 向客户端发送json数据 (以后不用自己写servletUtil工具了)
     * @param response
     * @param ackCode
     */
    public static void outJson(HttpServletResponse response, AckCode ackCode){
        response.setCharacterEncoding("UTF-8");
        R r= R.build(ackCode);
        //r--> json
        String jsonStr= JSONUtil.toJsonStr(r);
        cn.hutool.extra.servlet.ServletUtil.write(response,jsonStr, MediaType.APPLICATION_JSON_VALUE);
    }


    /**
     * 向客户端发送json数据 (以后不用自己写servletUtil工具了)
     * @param ackCode
     */
    public static void outJson( AckCode ackCode){
        //绑定当前请求线程
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setCharacterEncoding("UTF-8");

        R r= R.build(ackCode);
        //r--> json
        String jsonStr= JSONUtil.toJsonStr(r);
        cn.hutool.extra.servlet.ServletUtil.write(response,jsonStr, MediaType.APPLICATION_JSON_VALUE);
    }
}
